import { sceneAssistant } from '../index';
import { Rect } from './rect';
import { Points } from './points';

export class Gizmo {
    private color: cc.Color = cc.Color.RED;
    private rect: Rect | null = null;
    private points: Points | null = null;
    private gizmoRootNode: cc.Node | null = null;

    constructor() {
    }

    init(): cc.Node {
        const gizmoRootNode: cc.Node = new cc.Node('gizmo-root-node');

        this.rect = new Rect();
        const rectNode = this.rect.init({
            moveCallback: (event: cc.Event.EventTouch) => {
                const delta: cc.Vec2 = event.getDelta();
                const pos: cc.Vec2 | undefined = sceneAssistant.selectNode?.getPosition();
                if (pos) {
                    const p = pos.add(delta.divide(sceneAssistant.scale));
                    sceneAssistant.selectNode?.setPosition(p);
                }
                this._updateGizmoNodePosition();
                sceneAssistant.saveScene();
            },
        });
        gizmoRootNode.addChild(rectNode);
        this.gizmoRootNode = gizmoRootNode;
        this.points = new Points();
        this.points.init(gizmoRootNode);


        return gizmoRootNode;
    }

    _updateGizmoNodePosition():void {
        // gizmo和目标节点位置对齐了
        const selectNode: cc.Node | null = sceneAssistant.selectNode;
        if (selectNode) {
            const transform: cc.Node | null | undefined = this.gizmoRootNode?.parent;
            if (transform) {
                const worldPosition = selectNode.convertToWorldSpaceAR(cc.v2());
                const pos = transform.convertToNodeSpaceAR(worldPosition);
                this.gizmoRootNode?.setPosition(pos);
            }
        }
    }

    update():void {
        this._updateGizmoNodePosition();
        if (sceneAssistant.selectNode) {
            const { width, height } = sceneAssistant.selectNode.getContentSize();
            this.rect?.update(width, height);
            this.points?.update(width, height);
        } else {
            this.rect?.clean();
            this.points?.clean();
        }

    }

    syncSize(node: cc.Node | undefined | null):void {
        const size = node?.getContentSize();
        if (size) {
            // setNodeSize(this.graphicsComp?.node, size.width, size.height);
        }
    }
}